/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor. a
 */
package UI;

import Manejadores.ManejadorInicioSesion;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author Facundo
 */
public class ILogin extends javax.swing.JFrame {

    /**
     * Creates new form ILogin
     */
    ManejadorInicioSesion manejador;

    public ILogin() {
        manejador = new ManejadorInicioSesion();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLNombreUsuario = new javax.swing.JLabel();
        jTFNombreUsuario = new javax.swing.JTextField();
        jBIniciarSesion = new javax.swing.JButton();
        jBSalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bienvenido a Action Tracker!");
        setLocationByPlatform(true);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 0, 0));
        setMaximumSize(new java.awt.Dimension(416, 109));
        setMinimumSize(new java.awt.Dimension(416, 109));
        setPreferredSize(new java.awt.Dimension(400, 140));
        setResizable(false);

        jLNombreUsuario.setText("Usuario");

        jTFNombreUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTFNombreUsuarioKeyPressed(evt);
            }
        });

        jBIniciarSesion.setText("Iniciar sesión");
        jBIniciarSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBIniciarSesionActionPerformed(evt);
            }
        });

        jBSalir.setText("Salir");
        jBSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLNombreUsuario)
                        .addGap(20, 20, 20)
                        .addComponent(jTFNombreUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jBSalir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBIniciarSesion)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLNombreUsuario)
                    .addComponent(jTFNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBIniciarSesion)
                    .addComponent(jBSalir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setLocation(new java.awt.Point(400, 200));
    }// </editor-fold>//GEN-END:initComponents

    private void jBIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBIniciarSesionActionPerformed
        String nombreUsuario = this.jTFNombreUsuario.getText().toLowerCase();
        if (validar(nombreUsuario)) {
            //Me fijo si los datos de login son correctos.
            if (manejador.inicioSesion(nombreUsuario)) {
                //Si son correctos me fijo si es un usuario normal o administrador.
                if (manejador.checkearPrivilegioUsuarioLogueado().equals("administrador")) {
                    //Si es administrador llamo a la pantalla principal y le paso un true.
                    this.setVisible(false);
                    new IAcciones(true).setVisible(true);
                } else if (manejador.checkearPrivilegioUsuarioLogueado().equals("usuario")) {
                    //Si es usuario normal llamo a la pantalla principal y le paso un false.
                    this.setVisible(false);
                    new IAcciones(false).setVisible(true);
                } else {
                    //Esto es por si hay un error en la base de datos.
                    JOptionPane.showMessageDialog(this, "Error en el inicio de sesión.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }//Si no son correctos los datos de login aviso. 
            else {
                JOptionPane.showMessageDialog(this, "Nombre de usuario incorrecto o no habilitado", "Advertencia", JOptionPane.WARNING_MESSAGE);
            }
        }
       
        
    }//GEN-LAST:event_jBIniciarSesionActionPerformed

    private void jTFNombreUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTFNombreUsuarioKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            this.jBIniciarSesionActionPerformed(null);
        }
    }//GEN-LAST:event_jTFNombreUsuarioKeyPressed

    private void jBSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jBSalirActionPerformed

    private boolean validar(String nombreUsuario) {
        if (nombreUsuario.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Por favor ingrese todos los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        } else {
            return true;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the System look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ILogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ILogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ILogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ILogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ILogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBIniciarSesion;
    private javax.swing.JButton jBSalir;
    private javax.swing.JLabel jLNombreUsuario;
    private javax.swing.JTextField jTFNombreUsuario;
    // End of variables declaration//GEN-END:variables
}
